//
//  ViewController.swift
//  rmbtodollar-ios
//
//  Created by Mainzxq on 16/5/10.
//  Copyright © 2016年 Mainzxq. All rights reserved.
//

import UIKit
class ViewController: UIViewController {
    // 窗口控件初始化
    @IBOutlet weak var resultLbl: UILabel!
    @IBOutlet weak var sourceLbl: UILabel!
    @IBOutlet weak var alertBanner: UIView!
    @IBOutlet weak var alertLbl: UILabel!
    
    // 主程序变量
    var sourceCash: Double = 0.0
    var targetCash: Double = 0.0
    var sourceRate: Double = 0.0
    var sourceCurrency: String = "CNY"
    var targetCurrency: String = "USD"
    var currencyDict: NSDictionary = ["CNY":["USD":"0.15346", "JPY":"16.747566", "EUR":"0.134796"],
                                      "USD":["CNY":"6.5144",  "JPY":"109.15",    "EUR": "0.8785"],
                                      "JPY":["USD":"0.009163","EUR":"0.008049",  "CNY":"0.05971"],
                                      "EUR":["USD":"1.1383",  "JPY":"124.2222",  "CNY":"7.4186"]]
    
    // 计算器变量
    var tempNumber = ""
    var leftString = ""
    var rightString = ""
    var lastOperator = ""
    var reDict: NSDictionary = [:]
    var repeatCount: Int = 0
    
    // 动画状态：避免在动画未结束时又按下了更新汇率按钮，重复提交api处理会被ban
    var animateDidFinished:Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        alertBanner.alpha = 0.0
        sourceLbl.text = "0"
        resultLbl.text = "0"
        
        // 开始准备更新汇率字典
        let userDefaults = NSUserDefaults.standardUserDefaults()
        // 检测网络状态
        if testInternetStatus() {
            // 无历史数据
            if userDefaults.valueForKey("curDict") == nil {
                //执行同步更新（主线程挂起）
                updateCurrencyDict()
                print(currencyDict)
            } else {
                // 有历史数据， 执行异步更新，不影响主线程
                testNSThread()
                print(userDefaults.valueForKey("curDict"))
            }
            
            currencyDict = userDefaults.valueForKey("curDict") as! NSDictionary
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // 定义selectSegment行为
    @IBAction func targetValueChanged(sender: UISegmentedControl) {
        let segment: UISegmentedControl = sender
        
        switch segment.selectedSegmentIndex {
        case 0:
            print("USD")
            targetCurrency = "USD"
        case 1:
            print("Euro")
            targetCurrency = "EUR"
        case 2:
            print("Jpn")
            targetCurrency = "JPY"
        case 3:
            print("RMB")
            targetCurrency = "CNY"
        default:
            print("no")
        }
        calculateCash()
        
    }
    
    // 定义selectSegment行为
    @IBAction func sourceValueChanged(sender: UISegmentedControl) {
        let segment: UISegmentedControl = sender 
        
        switch segment.selectedSegmentIndex {
        case 0:
            print("USD")
            sourceCurrency = "USD"
        case 1:
            print("Euro")
            sourceCurrency = "EUR"
        case 2:
            print("Jpn")
            sourceCurrency = "JPY"
        case 3:
            print("RMB")
            sourceCurrency = "CNY"
        default:
            print("no")
        }
        calculateCash()
    }
    
    // 定义计算器数字区域和小数点的按钮
    @IBAction func buttonClick(sender: AnyObject) {
        let button = sender as! UIButton
        print(button.tag)
        switch button.tag {
            case 1000...1009:
                setValue(String(button.tag-1000))
            case 1010:
                setPoint()
            default:
                print("noting")
            }
        
        calculateCash()
    }
    
    @IBAction func clearBtn(sender: AnyObject) {
        resultLbl.text = "0"
        sourceLbl.text = "0"
        tempNumber = ""
    }
    
    @IBAction func euqalBtn(sender: AnyObject) {
        doCalc()
        lastOperator = ""
    }
    
    @IBAction func sumBtn(sender: AnyObject) {
        doCalc()
        lastOperator = "sum"
    }
    
    @IBAction func subtractionBtn(sender: AnyObject) {
        doCalc()
        lastOperator = "subtract"
        
    }
    
    @IBAction func backspaceBtn(sender: AnyObject) {
        // 没写回退键
    }
    
    // 定义汇率更新按钮的行为
    @IBAction func updateRate(sender: AnyObject) {
        if animateDidFinished {
            testNSThread()
        }
    }
    
    // 计算器运算逻辑处理
    func doCalc() {
        var resultNum: String! = ""
        // 如果缓存数据不存在，不做操作
        if tempNumber != "" {
            // 如果上次的操作符有记录，则直接进行计算
            if lastOperator != "" {
                // 将缓存值赋给右侧变量
                rightString = tempNumber
                switch lastOperator {
                    case "sum":
                        resultNum = ("\(Double(leftString)! + Double(rightString)!)")
                    case "subtract":
                        resultNum = ("\(Double(leftString)! - Double(rightString)!)")
                    case "divid":
                        resultNum = ("\(Double(leftString)! / Double(rightString)!)")
                    case "mutiple":
                        resultNum = ("\(Double(leftString)! * Double(rightString)!)")
                    default:
                        print("无法计算")
                }
                //将结果重新赋给左侧变量，等待下一次运算
                leftString = resultNum
                tempNumber = ""
            } else {
            //第一次按下运算符
                leftString = tempNumber
                resultNum = tempNumber
                tempNumber = ""
                
            }
            sourceLbl.text = resultNum
        }
        calculateCash()
    }
    
    // 定义实时转换汇率的方法，读取汇率字典中的汇率
    func calculateCash() {
        if targetCurrency == sourceCurrency {
            sourceRate = 1
        } else {
            let sourceCur = currencyDict[sourceCurrency] as! NSDictionary
            print(sourceCur[targetCurrency])
            sourceRate = sourceCur[targetCurrency]!.doubleValue
            print(String(format: "%.4f", sourceRate))
        }
        
        resultLbl.text = "\(Double(sourceLbl.text!)! * Double(String(format: "%.4f", sourceRate))!)"
       
    }
    
    // 处理按下小数点后的行为
    func setPoint() {
        //此处设计小数点算法，目前看应该可以优化
        if !(sourceLbl.text!.containsString(".")) {
            if sourceLbl.text! == "0" {
                print("点运算")
                sourceLbl.text! = "0."
                tempNumber = "0."
            } else {
                sourceLbl.text! += "."
                tempNumber += "."
            }
       } else if tempNumber == "" {
            print("点运算")
            sourceLbl.text! = "0."
            tempNumber = "0."
        }
        print(tempNumber + "点运算")
        
    }
    
    // 处理按下数字键盘后的行为
    func setValue(inStr: String!) {
        // 此时tempNumber
        tempNumber += inStr
        print(tempNumber + "字符设置运算")
        sourceLbl.text! = tempNumber
    }
    
    // 开线程，独立更新汇率字典
    func testNSThread(){
        //NSThread
        NSThread.detachNewThreadSelector(#selector(ViewController.updateCurrencyDict), toTarget: self, withObject: nil)
    }
    
    // 更新汇率字典方法
    func updateCurrencyDict() {
        let currencyDict1: NSMutableDictionary = [:]
        var serviceStatus: Bool = true
        for (k, v) in currencyDict {
            let cur: NSMutableDictionary = [:]
                for (key,_) in v as! NSDictionary {
                    if request(k as! String, toC: key as! String) != [:] {
                        cur.setValue((request(k as! String, toC: key as! String)["currency"]), forKey: key as! String)
                    } else {
                        serviceStatus = false
                        break
                    }
            }
            currencyDict1.setValue(cur, forKey: k as! String)
        }
        
        if serviceStatus {
            playPopBanner()
            saveDefaults(currencyDict1)
        } else {
            alertLbl.text = "无法获取API服务"
            playPopBanner()
            print("api服务挂了")
        }
        
    }
    
    // 检测互联网连接状态，这里是一个伪方法，真正实现应该是调用底层网络状态
    func testInternetStatus () -> Bool {
        var status: Bool = true
        let session = NSURLSession.sharedSession()
        session.dataTaskWithURL(NSURL(fileURLWithPath: "www.baidu.com")) { (data:NSData?, response: NSURLResponse?, error: NSError?) in
            if error != nil {
                status = false
                print("你的网络连接可能有问题！")
            }
        }
        return status
    }
    
    // 请求百度API，从百度汇率更新汇率字典
    func request(fromC: String, toC: String) -> NSDictionary {
        let urlStr = "http://apis.baidu.com/apistore/currencyservice/currency"
        let httpArg = "fromCurrency=\(fromC)&toCurrency=\(toC)&amount=1"
        let apiKey = "b93117cab57dac8d1412036532a76743"
        var myDict: NSDictionary! = [:]

        
        let req = NSMutableURLRequest(URL: NSURL(string: urlStr + "?" + httpArg)!)
        req.timeoutInterval = 6
        req.HTTPMethod = "GET"
        req.addValue(apiKey, forHTTPHeaderField: "apikey")
        let session = NSURLSession.sharedSession()
        let semaphore = dispatch_semaphore_create(0)
        let task = session.dataTaskWithRequest(req){ (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            if error == nil {
                do {
                    myDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary
                    // print(myDict)
                } catch {
                    print("can not serialized")
                }
                dispatch_semaphore_signal(semaphore)
            
            }
        }
            task.resume()
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
            // sleep(1)
        if (myDict["retData"]!.isKindOfClass(NSDictionary)) {
            myDict = myDict["retData"] as! NSDictionary
            repeatCount = 0
            return myDict
        } else {
            if repeatCount <= 3 {
                print("故障重来")
                repeatCount += 1
                return request(fromC, toC: toC)
            } else {
                print("api服务挂了")
                return [:]
            }
        }
    }
    
    // 将更新后的字典放入UserDefault
    func saveDefaults(dict: NSDictionary) {
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(dict, forKey: "curDict")
        defaults.synchronize()
    }
    
    
    // Animation
    func playPopBanner() {
        self.animateDidFinished = false
        alertBanner.alpha = 0
        // alertBanner.frame.origin.y = -alertBanner.frame.size.height
        UIView.animateWithDuration(2, delay: 0, options: (UIViewAnimationOptions.CurveEaseInOut), animations: {
            self.alertBanner.alpha = 1.0
            self.alertBanner.frame.origin.y += self.alertBanner.frame.size.height
            
        
            UIView.animateWithDuration(2, delay: 4, options: (UIViewAnimationOptions.OverrideInheritedDuration),
                    animations: {
                    
                    self.alertBanner.alpha = 0
                    self.alertBanner.frame.origin.y -= self.alertBanner.frame.size.height
                    },
                    completion: {finished -> Void in
                        
                        self.animateDidFinished = true
                })
            },completion: nil)
    }
}
// 五月十六日，这个项目暂时性完结，收获也不少，但是有很多不满意的地方。
// 未来努力的方向一个是尽量改良界面和易用性，另一方面要从客户的角度出发深入拓展需求。
